import dayjs from "dayjs";
import {
  OrganizationGetPage,
  OrganizationSave,
  OrganizationDelete,
  OrganizationUpdate
} from "@/api/admin/organization";
import { type PaginationProps } from "@pureadmin/table";
import { reactive, ref, onMounted, nextTick } from "vue";
import { ElMessage, ElMessageBox, FormInstance, uploadListEmits } from "element-plus";

export function useOrganization() {
  // 表单数据
  const form = reactive({
    OrganizationId: 0,
    OrganizationName: "",
    UserCount: 1,
    ExpirationTime: "",
    Remarks: ""
  });
  const dataList = ref([]);
  const loading = ref(true);
  const addPanelVisible = ref(false);
  const updatePanelVisible = ref(false);
  const loadingTitle = ref(undefined);
  const rules = {
    OrganizationName: [
      {
        required: true,
        message: "请输入机构名称！",
        trigger: ["blur", "change"]
      }
    ],
    UserCount: [
      {
        required: true,
        message: "请输入用户数量！",
        trigger: ["blur", "change"]
      }
    ],
    ExpirationTime: [
      {
        required: true,
        message: "请选择到期时间！",
        trigger: ["blur", "change"]
      }
    ]
  };
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    },
    {
      label: "机构名称",
      prop: "organizationName",
      minWidth: 200
    },
    {
      label: "用户数量",
      prop: "userCount",
      minWidth: 100
    },
    {
      label: "到期时间",
      minWidth: 180,
      prop: "expirationTime",
      formatter: ({ expirationTime }) =>
        dayjs(expirationTime).format("YYYY-MM-DD")
    },
    {
      label: "备注",
      prop: "remarks",
      minWidth: 300
    },
    {
      label: "创建时间",
      minWidth: 180,
      prop: "createTime",
      formatter: ({ createTime }) =>
        dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];

  async function handleUpdate(row: any | undefined) {
    if (row) {
      loadingTitle.value = "修改";
      nextTick(() => {
        form.OrganizationId = row.organizationId;
        form.OrganizationName = row.organizationName;
        form.UserCount = row.userCount;
        form.ExpirationTime = row.expirationTime;
        form.Remarks = row.remarks;
      });
    } else {
      loadingTitle.value = "添加";
      form.OrganizationId = 0;
    }
    updatePanelVisible.value = true;
  }

  async function handleDelete(row) {
    ElMessageBox({
      title: '提示', //MessageBox 标题
      closeOnClickModal: false,
      message: '是否确定删除当前项?', //MessageBox 消息正文内容
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      const res = await OrganizationDelete(row.organizationId);
      if (res.success) {
        ElMessage.success(res.msg);
        onSearch();
      } else {
        ElMessage.error(res.msg);
      }
    }).catch(() => { })
  }

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
    onSearch();
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  async function onSearch() {
    loading.value = true;
    const { data } = await OrganizationGetPage({
      pageindex: pagination.currentPage,
      pagesize: pagination.pageSize,
      ...form
    });
    dataList.value = data?.items;
    pagination.total = data?.totalCount;
    loading.value = false;
  }

  //添加机构 or 修改机构信息
  const addOrganization = (addDtoRef: FormInstance | undefined) => {
    (addDtoRef as any).validate(async valid => {
      if (!valid) return;
      let respone = null
      if (form.OrganizationId) {
        respone = await OrganizationUpdate(form);
      } else {
        respone = await OrganizationSave(form);
      }
      // const
      if (respone.success) {
        ElMessage({
          message: respone.msg,
          type: "success"
        });
        ClosePanelVisible(addDtoRef);
        onSearch();
      } else {
        ElMessage({
          message: respone.msg,
          type: "error"
        });
      }
    });
  };

  // 关闭
  function ClosePanelVisible(row: FormInstance | undefined) {
    if (!row) return;
    row.resetFields();
    updatePanelVisible.value = false;
  }

  const resetForm = formEl => {
    formEl.resetFields();
    updatePanelVisible.value = false;
  };

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    loadingTitle,
    addPanelVisible,
    updatePanelVisible,
    rules,
    onSearch,
    resetForm,
    handleUpdate,
    handleDelete,
    handleSizeChange,
    ClosePanelVisible,
    handleCurrentChange,
    handleSelectionChange,
    addOrganization
  };
}
